package com.todo.strategy.online.infrastructure.repository.impl;

import com.alibaba.fastjson.JSONObject;
import com.google.common.collect.Lists;
import com.todo.common.common.enums.BizErrorCodeEnum;
import com.todo.common.common.exception.BizException;
import com.todo.strategy.online.infrastructure.entity.po.WantSetPO;
import com.todo.strategy.online.infrastructure.mapper.WantSetMapper;
import com.todo.strategy.online.infrastructure.repository.WantSetRepository;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Repository;

import javax.annotation.Resource;
import java.util.List;

/**
 * (WantSet)表服务实现类
 *
 * @author zhangwenxiang
 * @since 2024-03-04 21:10:04
 */
@Slf4j
@Repository("wantSetRepository")
public class WantSetRepositoryImpl implements WantSetRepository {
    @Resource
    private WantSetMapper wantSetMapper;


    @Override
    public Boolean insertWantSetPO(WantSetPO wantSetPO) {
        if (wantSetPO == null) {
            throw new BizException(BizErrorCodeEnum.PARAM_ERROR);
        }
        if (!baseFieldCheck(wantSetPO)) {
            return false;
        }
        return wantSetMapper.insertWantSetPO(wantSetPO) > 0;
    }

    @Override
    public Boolean updateWantSetPOById(WantSetPO wantSetPO) {
        if (wantSetPO == null || wantSetPO.getId() == null) {
            throw new BizException(BizErrorCodeEnum.PARAM_ERROR);
        }
        if (!baseFieldCheck(wantSetPO)) {
            return false;
        }
        return wantSetMapper.updateWantSetPOById(wantSetPO) > 0;
    }


    @Override
    public Boolean removeWantSetPOById(Long id) {
        if (id == null || id < 0) {
            throw new BizException(BizErrorCodeEnum.PARAM_ERROR);
        }
        return wantSetMapper.removeWantSetPOById(id) > 0;
    }

    @Override
    public WantSetPO queryWantSetPOById(Long id) {
        if (id == null || id < 0) {
            return null;
        }
        return wantSetMapper.queryWantSetPOById(id);
    }

    @Override
    public List<WantSetPO> queryWantSetPOByUserId(Long userId) {
        if (userId == null || userId < 0) {
            return Lists.newArrayList();
        }
        return wantSetMapper.queryWantSetPOByUserId(userId);
    }

    private boolean baseFieldCheck(WantSetPO wantSetPO) {
        if (wantSetPO == null) {
            return false;
        }
        if (wantSetPO.getUserId() == null || wantSetPO.getStartPlanTime() == null || wantSetPO.getEndPlanTime() == null) {
            log.warn("WantSetRepository#baseFieldCheck 核心字段校验失败，默认不操作 wantSetPO：【{}】", JSONObject.toJSONString(wantSetPO));
            return false;
        }
        if (wantSetPO.getStartPlanTime().after(wantSetPO.getEndPlanTime())) {
            log.warn("WantSetRepository#baseFieldCheck 开始时间大于结束时间，默认不操作 wantSetPO：【{}】", JSONObject.toJSONString(wantSetPO));
            return false;
        }
        //间隔X天不操作-或方service层
        return true;
    }
}
